package com.cws.project.cws.student.controller;

import com.cws.common.constant.UserConstants;
import com.cws.common.utils.StringUtils;
import com.cws.common.utils.poi.ExcelUtil;
import com.cws.framework.aspectj.lang.annotation.Log;
import com.cws.framework.aspectj.lang.enums.BusinessType;
import com.cws.framework.web.controller.BaseController;
import com.cws.framework.web.domain.AjaxResult;
import com.cws.framework.web.page.TableDataInfo;
import com.cws.project.cws.clazz.domain.Clazz;
import com.cws.project.cws.clazz.service.IClazzService;
import com.cws.project.cws.student.domain.Student;
import com.cws.project.cws.student.service.IStudentService;
import com.cws.project.system.role.service.IRoleService;
import com.cws.project.system.user.domain.User;
import com.cws.project.system.user.service.IUserService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 * @author XYL
 * @date 2021-12-22 9:48
 */
@Controller
@RequestMapping("/cws/student")
public class StudentController extends BaseController {
    private String prefix = "cws/student" ;

    @Autowired
    private IUserService userService;

    @Autowired
    private IStudentService studentService;

    @Autowired
    private IClazzService clazzService;

    @RequiresPermissions("cws:student:list")
    @GetMapping()
    public String clazz() {
        return prefix + "/student" ;
    }

    @RequiresPermissions("cws:student:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(Student stu) {
        startPage();
        //当前辅导员id，
        User sysUser = getSysUser();
        List<Student> list = new ArrayList<>();
        //是否是管理员
        if(sysUser.isInstructor() || sysUser.isTeacher()){
            stu.setUserId(sysUser.getUserId());
            list = studentService.selectStudentList(stu);
        }
        if(sysUser.isAdmin()){
            stu.setUserId(null);
            list = studentService.selectStudentList(stu);
        }
        return getDataTable(list);
    }


    /**
     * 查询学生信息列表，根据课程Id
     */
    @RequiresPermissions("cws:student:list:clazzId")
    @GetMapping("/list/{clazzId}")
    public String listByClazzId(@PathVariable("clazzId") Long clazzId,ModelMap mmap) {
        mmap.put("clazzId",clazzId);
        return prefix + "/student" ;
    }

    @Log(title = "学生管理" , businessType = BusinessType.EXPORT)
    @RequiresPermissions("cws:student:export")
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(Student stu) {
        startPage();
        //当前辅导员id，
        User sysUser = getSysUser();
        List<Student> list = new ArrayList<>();
        //是否是管理员
        if(sysUser.isInstructor() || sysUser.isTeacher()){
            stu.setUserId(sysUser.getUserId());
            list = studentService.selectStudentList(stu);
        }
        if(sysUser.isAdmin()){
            stu.setUserId(null);
            list = studentService.selectStudentList(stu);
        }
        ExcelUtil<Student> util = new ExcelUtil<>(Student.class);
        return util.exportExcel(list, "学生数据");
    }

    /**
     * 新增学生
     */
    @GetMapping("/add")
    public String add(ModelMap mmap) {
        User sysUser = getSysUser();
        if(sysUser.isAdmin()){
            sysUser.setUserId(null);
        }
        List<Clazz> list = clazzService.selectClazzListByUserId(sysUser.getUserId());
        mmap.put("clazzs",list);
        return prefix + "/add" ;
    }

    /**
     * 新增保存学生
     */
    @RequiresPermissions("cws:student:add")
    @Log(title = "学生管理" , businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(@Validated Student stu) {
        if (UserConstants.USER_NAME_NOT_UNIQUE.equals(userService.checkLoginNameUnique(stu.getLoginName()))) {
            return error("新增学生'" + stu.getLoginName() + "'失败，学号已存在");
        } else if (StringUtils.isNotEmpty(stu.getPhonenumber())
                && UserConstants.USER_PHONE_NOT_UNIQUE.equals(userService.checkPhoneUnique(stu))) {
            return error("新增学生'" + stu.getLoginName() + "'失败，手机号码已存在");
        } else if (StringUtils.isNotEmpty(stu.getEmail())
                && UserConstants.USER_EMAIL_NOT_UNIQUE.equals(userService.checkEmailUnique(stu))) {
            return error("新增学生'" + stu.getLoginName() + "'失败，邮箱账号已存在");
        }
        return toAjax(studentService.insertStudent(stu));
    }

    /**
     * 修改学生
     */
    @GetMapping("/edit/{userId}")
    public String edit(@PathVariable("userId") Long userId, ModelMap mmap) {
        User sysUser = getSysUser();
        if(sysUser.isAdmin()){
            sysUser.setUserId(null);
        }
        List<Clazz> list = clazzService.selectClazzListByUserId(sysUser.getUserId());
        mmap.put("clazzs",list);

        Student student = studentService.selectUserById(userId);
        mmap.put("student" , student);
        return prefix + "/edit" ;
    }

    /**
     * 修改保存学生
     */
    @RequiresPermissions("cws:student:edit")
    @Log(title = "学生管理" , businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(@Validated Student stu) {
        userService.checkUserAllowed(stu);
        if (StringUtils.isNotEmpty(stu.getPhonenumber())
                && UserConstants.USER_PHONE_NOT_UNIQUE.equals(userService.checkPhoneUnique(stu))) {
            return error("修改学生'" + stu.getLoginName() + "'失败，手机号码已存在");
        } else if (StringUtils.isNotEmpty(stu.getEmail())
                && UserConstants.USER_EMAIL_NOT_UNIQUE.equals(userService.checkEmailUnique(stu))) {
            return error("修改学生'" + stu.getLoginName() + "'失败，邮箱账号已存在");
        }
        return toAjax(studentService.updateStudent(stu));
    }

    @RequiresPermissions("cws:student:remove")
    @Log(title = "学生管理" , businessType = BusinessType.DELETE)
    @PostMapping("/remove")
    @ResponseBody
    public AjaxResult remove(String ids) {
        return toAjax(userService.deleteUserByIds(ids));
    }



}
